﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace FizzBuzz
{
    class SocketDemo
    {
        public void Run()
        {
            StartServer();
            StartClient();
//            Socket server = new Socket(AddressFamily.InterNetwork, 
//                SocketType.Dgram, ProtocolType.Udp);
//            server.Bind(new IPEndPoint(IPAddress.Any, 18080));
//            server.Listen(5);
        }

        public void StartServer()
        {
            TcpListener listener = new TcpListener(IPAddress.Any, 10808);
            listener.Start();

            for(;;)
            {
                TcpClient client = null;
                NetworkStream stream = null;

                client = listener.AcceptTcpClient();
                stream = client.GetStream();
                Console.WriteLine("Handling client");
                byte[] receiveBuffer = new byte[1024];
                int bytesReceived;
                int totalBytesEchoed = 0;
                while( (bytesReceived = stream.Read(receiveBuffer, 0, receiveBuffer.Length)) > 0)
                {
                    stream.Write(receiveBuffer, 0, bytesReceived);
                    totalBytesEchoed += bytesReceived;
                }

                stream.Close();
                client.Close();
            }
        }

        public void StartClient()
        {
            string server = "127.0.0.1";
            byte[] bytesBuffer = Encoding.ASCII.GetBytes("word");

            TcpClient client = new TcpClient("127.0.0.1", 10808);
            Console.WriteLine("Connected to server");
            NetworkStream stream = client.GetStream();
            stream.Write(bytesBuffer, 0, bytesBuffer.Length);

            int totalBytesReceived = 0;
            int bytesReceived = 0;

            while(totalBytesReceived < bytesBuffer.Length)
            {
                if ((bytesReceived = stream.Read(bytesBuffer, 0, bytesBuffer.Length)) > 0)
                {
                    
                }
            }
        }
    }
}
